import { Types, defineComponent, type IWorld, type Entity, hasComponent, removeComponent, type Component } from '$lib/ecs';

const skills = new Map();

export const defineSkill = (skill) => {
  const comp = defineComponent(skill, {
    amount: Types.i32,
  });
  skills.set(skill, comp);
  return comp;
};

export const FreeSkills = defineComponent('FreeSkills', {
  amount: Types.i32,
});

export const enumSkills = () => Array.from(skills.entries());

export const getSkill = (name) => skills.get(name);

export const enumAvailableSkills = (world: IWorld, e: Entity) => enumSkills().filter(([_, skill]) => hasComponent(world, skill, e));

export const purgeSkills = (world: IWorld, e: Entity) => {
  for (let [_, skill] of enumSkills()) {
    if (hasComponent(world, skill, e)) {
      removeComponent(world, skill, e);
    }
  }
};

export const getSkillLevel = (world: IWorld, e: Entity, skill: Component) => {
  return hasComponent(world, skill, e) ? skill.amount[e] : 0;
};
